package com.zcf.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zcf.constant.Constants;
import com.zcf.utils.JwtUtil;
import com.zcf.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zcf
 */
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        //判断token是否为空
        if(!StringUtils.hasLength(token)){
           return true;
        }
        //如果有令牌，需要解析验证，如果不对，拦截，对，就放行

            //1.要从redis中获取token
            String redisToken = stringRedisTemplate.opsForValue().get(Constants.LOGIN_KEY + token);
           if(StrUtil.isBlank(redisToken)){
              return true;
           }
            Map<String, Object> map = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(map);

            //刷新token有效期
        stringRedisTemplate.expire(Constants.LOGIN_KEY+token,1, TimeUnit.HOURS);
            return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
